/**
 * 配置
 */
<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>{{title}}</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 搜索筛选 -->
		<el-form :inline="true" :model="formInline" class="user-setting">
			<el-row :gutter="20">
				<el-col :span="12">
					<el-divider content-position="left">
						<span style="color: red; font-weight: bold; font-size: 22px">
							当前操作：{{ title }}
						</span>
					</el-divider>
					<!-- 前端配置 -->
					<div class="grid-content ep-bg-purple">
						<div
							style="
								margin: 20px 0px;
								font-size: 18px;
								font-weight: bold;
								width: 100%;
							"
						>
							<span>前台配置： </span>
						</div>
						<div class="ep-form-item" style="width: 100%">
							<span>前台地址：</span>
							<el-input
								size="large"
								v-model="formInline.frontloginurl"
								placeholder="输入地址"
								style="width: 80%"
								disabled
							>
							</el-input>
						</div>
						<div class="ep-form-item" style="width: 90%;">
							<el-table :data="fronttableData" style="width: 100%;"  ref="multipleTable" @select="rowClick" height="300" max-height="300" @select-all="allrowclick">
								<el-table-column type="selection" width="55"></el-table-column>
								<el-table-column property="user_name" label="前台账号" width="150" header-align="center" align="center"></el-table-column>
								<el-table-column property="user_pwd" label="前台密码"	width="200" header-align="center" align="center"  :show-overflow-tooltip="true">
								</el-table-column>
								<el-table-column fixed="right"	label="操作" width="150" header-align="center">
									<template slot-scope="scope">
										<el-button @click="deleteClick(scope.row)" type="danger" size="mini">删除</el-button>
										<el-button type="danger" size="mini" @click="editClick(scope.row)">编辑</el-button>
									</template>
								</el-table-column>
							</el-table>	
							<el-button class="mt-4" style="width: 100%" @click="onAddItem('1')">
								+增加
							</el-button>	
						</div>
					</div>
				</el-col>
				<el-col :span="12">
					<el-divider content-position="left">
						<span style="color: red; font-weight: bold; font-size: 22px">
							<!-- 前台账号：{{ formInline.frontusername }}；后台账号：{{formInline.backusername}} -->
						</span>
					</el-divider>
					<div class="grid-content ep-bg-purple">
						<div style="margin: 20px 0px; font-size: 18px; font-weight: bold">
							<span>后台配置：</span>
						</div>
						<div class="ep-form-item" style="width: 100%">
							<span>后台地址：</span>
							<el-input
								size="large"
								v-model="formInline.backloginurl"
								placeholder="输入地址"
								style="width: 80%"
								disabled
							>
							</el-input>
						</div>
						<div class="ep-form-item" style="width: 90%">
							<el-table :data="backtableData" style="width: 100%;"  ref="backmultipleTable" @select="rowClick" height="300" max-height="300" @select-all="allbackrowclick">
								<el-table-column type="selection" width="55"></el-table-column>
								<el-table-column property="user_name" label="后台账号" width="150" header-align="center" align="center"></el-table-column>
								<el-table-column property="user_pwd" label="后台密码"	width="200" header-align="center" align="center"  :show-overflow-tooltip="true">
								</el-table-column>
								<el-table-column fixed="right"	label="操作" width="150" header-align="center">
									<template slot-scope="scope">
										<el-button @click="deleteClick(scope.row)" type="danger" size="mini">删除</el-button>
										<el-button type="danger" size="mini" @click="editClick(scope.row)">编辑</el-button>
									</template>
								</el-table-column>
							</el-table>	
							<el-button class="mt-4" style="width: 100%" @click="onAddItem('0')">
								+增加
							</el-button>					
						</div>
					</div>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<div>
					<el-col :span="24">
						<el-form-item	label="跟单设置："	style="font-size: 18px; font-weight: bold">
							<el-checkbox v-model="isStart">自动跟单</el-checkbox>
						</el-form-item>
					</el-col>
				</div>
				<div>
					<el-col :span="24">
						<el-form-item	label="记录处理："	style="font-size: 18px; font-weight: bold">
							<el-button	size="small" type="primary"	icon="el-icon-delete"	@click="cleanOrder" style="width: 150px;">
								清除记录
							</el-button>
						</el-form-item>
					</el-col>
				</div>
				<div>					
					<el-col :span="24"  style="margin-bottom: 30px; ">
						<span style="font-size: 14px; font-weight: bold;">跟单模式：
					 	<el-radio-group v-model="ordermode.start" @change="orderMode(ordermode.start)">
							<el-radio :label="0">正向跟单</el-radio>
							<el-radio :label="1">反向跟单</el-radio>
						</el-radio-group>
					</span>
					</el-col>				
				</div>
				<el-col :span="24">
					<el-form-item
						label="跟单比例："
						style="font-size: 18px; font-weight: bold"
					>
					</el-form-item>
					<el-input-number
						v-model="formInline.tracepercent"
						:precision="0"
						:step="1"						
					/>
					<el-button
						size="small"
						type="primary"
						icon="el-icon-search"
						@click="savetracepercent"
						style="width: 150px; margin-left: 50px"
						>立即生效</el-button
					>
				</el-col>
			</el-row>
			<div style="display: flex;justify-content: center; align-items: center;">	
				<el-button
						size="small"
						type="primary"
						icon="el-icon-search"
						@click="saveSetting"
						style="width: 300px;"
						>保存</el-button
					>
					<el-button
						size="small"
						type="danger"
						icon="el-icon-female"  
						@click="saveReboot"
						style="width: 300px"
						:disabled="isDisabled"						
						>{{butText}}</el-button
					>
		    </div>
		</el-form>		
		<el-divider />	
		<!-- 添加用户界面 -->	    
		<el-dialog title="增加新用户" :visible.sync="editFormVisible" width="30%" @click='closeDialog("add")'>
			<el-form label-width="100px" ref="editForm" :model="editForm" :rules="rules">
				<el-form-item label="账号：" prop="username">
				<el-input size="small" v-model="editForm.username" auto-complete="off" placeholder="请输账号"></el-input>
				</el-form-item>
				<el-form-item label="密码：" prop="userpwd">
				<el-input size="small" v-model="editForm.userpwd" placeholder="请输入密码"></el-input>
				</el-form-item>
				<!-- <el-form-item label="确认密码：" prop="itemunit">
				<el-input size="small" v-model="editForm.reitempws" placeholder="请输入确认密码"></el-input>
				</el-form-item> -->
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="small" @click='closeDialog("add")'>取消</el-button>
				<el-button size="small" type="primary" :loading="loading" class="title" @click="submitAddForm('editForm')">增加</el-button>
			</div>
		</el-dialog>
		<!-- 添加用户界面 -->	    
		<el-dialog title="编辑用户" :visible.sync="edituserVisible" width="30%" @click='closeDialog("edit")'>
			<el-form label-width="100px" ref="editForm" :model="editForm" :rules="rules">
				<el-form-item label="账号：" prop="username">
				<el-input size="small" v-model="editForm.username" auto-complete="off" placeholder="请输账号"></el-input>
				</el-form-item>
				<el-form-item label="密码：" prop="userpwd">
				<el-input size="small" v-model="editForm.userpwd" placeholder="请输入密码"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="small" @click='closeDialog("edit")'>取消</el-button>
				<el-button size="small" type="primary" :loading="loading" class="title" @click="submiteditForm('editForm')">更新</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
	ConfigisStart,
	ConfigdistrictsSave,
	ConfigPercent,
	ConfigSetInfo,
	ConfigReboot,
	ConfigRebootStatus,
	ConfigGetOderMode,
	ConfigSetOderMode,
	ConfigGetUserpws,
	saveAddClassify,
	ConfigPutUsersStart,
	ConfigDeleteUsers,
	ConfigEditUsers,
	ConfigClearOrders
} from "../../api/basisMG";
import { getPort, mathString } from "../../utils/util";
export default {
	data() {
		return {
			loading: false, //是显示加载
			editFormVisible: false, //控制添加用户页面显示与隐藏
			edituserVisible: false, //控制编辑用户页面显示与隐藏
			title: "",
			formInline: {
				frontloginurl: "",
				backloginurl: "",
				tracepercent: 0, // 跟单比例
				start: 0, ///是否自动跟单
			},
			isStart: false, ///是否自动跟单
			port: "0", ////获取当前组件接口的端口号			
			// 接口获取回来的存储在checkboxOptions
			checkboxOptions: [],
			districtOptons: [
				{ name: "是否自动跟单", index: 1, ischeck: true },
				// {"name":'古楼乡',"index":2,"ischeck":true},
			],
			// 重启后按钮变化
			butText:'重启',
			isDisabled: false,

			// 跟单模式
			ordermode:{
				start : 0
			},
			// 编辑与添加
			editForm: {	
				userid : '', ///ID			
				username :'',  //账号
				userpwd :'', ///密码
			},
			// 前后台的类型：0表示后台类型，1表示跟单前端类型
			webtype:"0",

            // 验证两次密码输入一致
			rules: {
				username:[
					{ required: true, message: '请输入账号', trigger: 'blur' }				
				],
				userpwd:[
					{ required: true, message: '请输入密码', trigger: 'blur' },
					{ min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
				],
				// reitempws:[
				// 	{ required: true, message: '请再次输入密码', trigger: 'blur' },
				// 	{ validator: (rule, value, callback) => {
				// 		if (value !== this.editForm.itempws) {
				// 			callback(new Error('两次输入的密码不一致'));
				// 		} else {
				// 			callback();
				// 		}
				// 	}, trigger: 'blur' }
				// ]
			},
			// 前台账号密码
			fronttableData: [],
			// 后台账号密码
			backtableData: [],
		};
	},
	/**
	 * 创建完毕
	 */
	created() {
		this.title = this.$route.name;
		// console.log("config-routername", this.title);
		// 将当前组件页写入localstorage
		// 获取当前路由组件的端口号
		// const match = this.title.match(/\d+/);
		// const index = parseInt(match[0], 10);
		// this.port = getPort(index - 1);
		// 通过页面名称转为端口号
		this.port = mathString(this.title)
		// console.log("config-name:", this.port);
		this.getdata(this.formInline);
	},

	// 监控
	watch: {
		// 监听isStart是否变化
		isStart: {
			handler(newVal, oldVal) {
				// console.log("isStart变化了，当前为：", this.isStart);
				// 若自动跟单选项框有变化，就调用接口保存
				this.saveisStart();
			},
			deep: true, ////开启深度监听
		},
	},

	/**
	 * 里面的方法只有被调用才会执行
	 */
	methods: {
		/***
		 * 调用接口，获取前台配置 1-前台
		*/
		getFrontTableData(){
			ConfigGetUserpws(1,this.port)
			    .then((res) => {
					// console.log('前台配置：',res,this.multipleSelection)
					this.fronttableData = res.data.data.userlist
					// 判断哪些是打勾的记录
					// $nextTick 主要作用是延迟DOM更新和简化异步操作，主要用于接口回调时的异步处理。
					this.$nextTick(() => {
						this.fronttableData.forEach((row) => {
							// console.log('前台配置-1：',row)
							if (parseInt(row.is_start) == 1) {
							   this.$refs.multipleTable.toggleRowSelection(row, true);
							}
						});
					});
				})
				.catch((err) => {

				})
		},
		/***
		 * 调用接口，获取前台配置 0-后台
		*/
		getBackTableData(){
			ConfigGetUserpws(0,this.port)
			    .then((res) => {
					// console.log('后台配置：',res)
					this.backtableData = res.data.data.userlist
					// 判断哪些是打勾的记录
					// $nextTick 主要作用是延迟DOM更新和简化异步操作，主要用于接口回调时的异步处理。
					this.$nextTick(() => {
						this.backtableData.forEach((row) => {
							if (parseInt(row.is_start) == 1) {
							   this.$refs.backmultipleTable.toggleRowSelection(row, true);
							}
						});
					});

				})
				.catch((err) => {

				})	
		},
		/***
		 * 获取设置内容
		*/
		getdata(parameter) {
			this.loading = true;
            //调用接口，获取前台配置 
			this.getFrontTableData()
            // 调用接口，获取后台配置
			this.getBackTableData()
			//调用接口，获取配置信息
			ConfigSetInfo(this.port)
				.then((res) => {
					// console.log('调用配置：',res)
					let setDate = res.data.data.sysparms;
					this.loading = false;
					if (setDate == "") {
						this.$message({
							type: "info",
							message: "数据为空",
						});
					} else {
						this.formInline.frontloginurl = setDate.frontweb.loginurl;
						this.formInline.backloginurl = setDate.backweb.loginurl;
						this.formInline.tracepercent = setDate.traceparams.tracepercent;
						this.isStart = parseInt(setDate.starttrace.start) == 1 ? true : false;
					}
				})
				.catch((err) => {
					this.loading = false;
					// this.$message.error("加载失败，请稍后再试！");
					this.$alert(
						"<strong style='color:red;font-size:20px;'>" +
							this.title +
							"</strong>" +
							"  未开通或未配置数据！！",
						"提示",
						{ dangerouslyUseHTMLString: true }
					);
				});
			//调用接口，获取下单模式	
			ConfigGetOderMode(this.port)
			.then((res) => {				
				let getMode = res.data.data
				// console.log('获取下单模式：', getMode)
				// 将字符串型转为数字型 
				this.ordermode.start = parseInt(getMode.revert_status)

			})
			.catch((err) =>{
				this.$message.error("加载失败，请稍后再试！");
			})
		},

		// 显示创建新用户的编辑框
		onAddItem(type){
			this.editFormVisible = true
			// 确认增加是前台还是后台的用户
			this.webtype = type
			this.editForm = {
				userid : '', ///ID			
				username :'',  //账号
				userpwd :'', ///密码
			}
		},
		// 关闭编辑、添加弹出框
		closeDialog(dialog) {
			if (dialog == 'edit') {
				this.edituserVisible = false
			} else if (dialog == 'add'){
				this.editFormVisible = false
			}
		},

        // 增加新用户
		submitAddForm(addData){
			this.$refs[addData].validate(valid =>{
				if(valid){
					let  add_new_webuser = {}
					// 当webtype=1时为增加前台用户，webtype=0时为增加后台用户
					if(parseInt(this.webtype) == 1){
						add_new_webuser = {
							"webhost":this.formInline.frontloginurl,
							"webtype":this.webtype,
							"username":this.editForm.username,
							"userpwd":this.editForm.userpwd
					   }
					}else{
						add_new_webuser = {
							"webhost":this.formInline.backloginurl,
							"webtype":this.webtype,
							"username":this.editForm.username,
							"userpwd":this.editForm.userpwd
					    }
					}				

					// console.log('addData-1:',add_new_webuser)
					// 调用新增用户接口
					saveAddClassify(add_new_webuser,this.port)
					   .then((res) => {
							// console.log('addData-2:',res)
							// 新增完成后，重新刷新页面
							this.$nextTick(() =>{
								this.editFormVisible = false
								this.getFrontTableData()
								this.getBackTableData()
							})
					   })
					   .catch((error) => {

					   })
				}
			})
		},

        // 跟单模式变化时进行变量赋值
		orderMode(value){        
		   this.ordermode.start = value
		   // 保存下单模式    
		   ConfigSetOderMode(this.ordermode, this.port)
		   .then((res) => {
			//    console.log('跟单模式保存成功', res)
			   if(res.msg !='设置下单模式成功'){
				this.$message({
							type: "info",
							message: "下单模式保存失败",
						});
			   }
		   })
		   .catch(() => {
			  this.$message.error("加载失败，请稍后再试！");
		   })
		},

		// 勾选某行时存储到服务端
		rowClick(selection,row){
			let web_users_start = {}
			
			if(parseInt(row.is_start) == 0){
				web_users_start = {
					userid: row.webuser_id,
					start: 1					
				}
			}else{
				web_users_start = {
					userid: row.webuser_id,
					start: 0					
				}
			}
			// console.log('rowclick:',web_users_start)
			// 调用打勾/取消的接口
			this.updateWebUserstart(web_users_start,this.port)

		},

		// 调用打勾/取消的接口
		updateWebUserstart(userstart,port){
			ConfigPutUsersStart(userstart,port)
			   .then((res) => {
					console.log('rowclick打勾：',res)

			   })
			   .catch((err) => {

			   })
		},

		// 前台全选/全取消时
		allrowclick(selection){
			// console.log('allrowclick',selection,selection.length)
			if(selection.length > 0){
				// 全选并调用打勾接口
				for(var i=0; i<selection.length; i++){
					let allUserStart = {
						userid: selection[i].webuser_id,
						start: 1	
					}
					this.updateWebUserstart(allUserStart,this.port)
				}
			}else{
				// 取消并调用打勾接口
				for(var i=0; i<this.fronttableData.length; i++){
					let allUserStart = {
						userid: this.fronttableData[i].webuser_id,
						start: 0	
					}
					this.updateWebUserstart(allUserStart,this.port)
				}
			}
		},

		// 后台全选/全取消时
		allbackrowclick(selection){
			// console.log('allrowclick',selection,selection.length)
			if(selection.length > 0){
				// 全选并调用打勾接口
				for(var i=0; i<selection.length; i++){
					let allUserStart = {
						userid: selection[i].webuser_id,
						start: 1	
					}
					this.updateWebUserstart(allUserStart,this.port)
				}
			}else{
				// 取消并调用打勾接口
				for(var i=0; i<this.backtableData.length; i++){
					let allUserStart = {
						userid: this.backtableData[i].webuser_id,
						start: 0	
					}
					this.updateWebUserstart(allUserStart,this.port)
				}
			}
		},

		// 删除记录
		deleteClick(row){
			// console.log('deleteclick:',row)
			let webuser = {
				userid: row.webuser_id
			}
			this.$confirm('确定删除此用户？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() =>{
				ConfigDeleteUsers(webuser,this.port)
			   .then((res) => {
				// console.log('deleteClick',res)
				 this.$nextTick(() =>{
					this.getFrontTableData()
					this.getBackTableData()
				 })
				 this.$message({
					type: 'info',
					message: '删除成功！！！'
				}); 

			   })
			   .catch((err) => {
					this.$message({
						type: 'info',
						message: '服务端操作失败！'
					}); 
			   })

			})
			.catch(() => {
				this.$message({
					type: 'info',
					message: '取消删除'
				}); 
			})

		},

		// 显示编辑界面
		editClick(row){
			this.edituserVisible = true
			this.editForm = {	
				userid : row.webuser_id,			
				username :row.user_name,
				userpwd : row.user_pwd
			}
		},

		// 更新用户
		submiteditForm(){
			ConfigEditUsers(this.editForm, this.port)
			  .then((res) => {
				// console.log('更新：', res)
				this.edituserVisible = false
				this.$nextTick(() =>{
					this.getFrontTableData()
					this.getBackTableData()
				 })
			  })
			  .catch((err) => {

			  })
		},

		// 状态转换
		BooleantoInt() {
			if (this.isStart == true) {
				this.formInline.start = 1;
			} else {
				this.formInline.start = 0;
			}
		},

		// 清除记录
		cleanOrder(){
			ConfigClearOrders('',this.port)
			.then((res) => {
				// console.log('cleanOrder',res)
				if (res.msg == '清理历史订单成功'){
					this.$message({
						type: 'info',
						message: '清理历史订单成功！'
					}); 
				}else{
					this.$message({
						type: 'info',
						message: '清理历史订单失败！'
					}); 
				}
			})
			.catch(() => {
				this.$message({
						type: 'info',
						message: '清理历史订单失败！'
					}); 
			})

		},
		// 全局保存设置内容
		saveSetting() {
			// 全局保存api/update_sysparams:修改配置信息
			this.saveDistricts();
		},
		// 全局保存设置
		saveDistricts() {
			// console.log("saveDistricts-1:", this.formInline);
			// 将 formInline 对象转换为 JSON 字符串
			// const jsonData = JSON.stringify(this.formInline);
			this.BooleantoInt();
			// 调用全局保存保存接口
			ConfigdistrictsSave(this.formInline, this.port)
			.then((res) => {
				console.log("saveDistricts:", res);
			})
			.catch(() => {

			})
		},
		// 保存自动跟单设置
		saveisStart() {
			this.BooleantoInt();
			// 转成对象
			const start = { start: this.formInline.start };
			ConfigisStart(start, this.port).then((res) => {
				// console.log("saveisStart:", res);
			});
		},

		// 保存跟单比例
		savetracepercent() {
			// 转成对象
			const tracepercent = { tracepercent: this.formInline.tracepercent };
			ConfigPercent(tracepercent, this.port)
				.then((res) => {
					console.log("savetracepercent:", res);
				})
				.catch((err) => {
					this.loading = false;
					this.$message.error("保存失败，请稍后再试！");
				});
		},
		// 重启
		saveReboot(){
			ConfigReboot('1',this.port).then((res) =>{
				this.butText = '重启中......'
				this.isDisabled = true
				// console.log('ConfigReboot', res.data.data)
				// console.log('reboot', res)				
				// 启动定时器，每5秒调用一次reBootStatus函数
				let intervalid = setInterval(() => {
					ConfigRebootStatus(this.port).then((res) =>{
						// console.log('rebootstatus', res.data.data)
						let statusData = res.data.data
						if (parseInt(statusData.back_status) === 0 && parseInt(statusData.front_status) === 0){
							// console.log('rebootstatus-1完成', res.data.data)
							// 清除定时器
							clearInterval(intervalid);
							this.butText = '重启'
							this.isDisabled = false
						}
						// else{
						// 	console.log('rebootstatus-2过程中', res.data.data)
						// }
				    })
				},10000)	
			})

		},
	},
};
</script>

<style scoped>

.user-setting {
	margin: 20px 10px;
}
.userRole {
	width: 100%;
}

.setstyle {
	border: 1px solid #c7c3c3;
}

.stycol {
	margin: 20px 300px;
	width: 700px;
}

/* demo */
.el-row {
	margin-bottom: 20px;
}
.el-row:last-child {
	margin-bottom: 0;
}
.el-col {
	border-radius: 4px;
}

.grid-content {
	border-radius: 4px;
	min-height: 36px;
	border: 1px solid #e3e9f1;
	padding-left: 20px;
}

.ep-form-item {
	margin: 20px 0.1em;
	font-size: 1em;
}
</style>


